import axios from 'axios';
// import { Notification } from 'element-ui';
import qs from 'qs'; // fromData 转 string
import store from '@/store';
import appName from '@/utils/environments';

let ApiVersion = '/api'; // 默认请求地址
if (appName === 'tronNewdex') {
  ApiVersion = '/tronapi';
}
const https = axios.create({
  baseURL: ApiVersion,
  timeout: 20000,
  auth: {
    username: localStorage.getItem('Frontend-Token') || '', // TokenKey = 'Frontend-Token';
  },
});

https.defaults.transformRequest = [(data, header) => { // 开始请求前期
  const headerThis = header;
  headerThis.account = null;
  headerThis.channel = 'web';
  if (appName === 'tronNewdex') {
    headerThis.chain = 'tron';
    headerThis.project = 'tron';
  }
  if (appName === 'eosNewdex') {
    headerThis.chain = 'eos';
    headerThis.project = 'newdex';
  }
  if (store.state.app.scatter && store.state.app.scatter.identity) {
    headerThis.account = store.state.app.scatter.identity.accounts[0].name;
    const wallet = store.state.app.scatter.wallet;
    if (wallet) {
      headerThis.ref = encodeURI(wallet)
      headerThis.chain = store.state.app.scatter.chain || 'eos';
    }
  }
  headerThis.language = store.state.app.language || 'en';
  const token = localStorage.getItem('Frontend-Token');
  if (token) { // 更新token
    headerThis.token = token; // eslint-disable-line
  }
  if (!header['Content-Type']) {
    return qs.stringify(data);
  }
  return data;
}];

https.interceptors.request.use((config) => { // 请求前期后
  // console.log(config);
  const token = localStorage.getItem('Frontend-Token');
  if (token) { // 更新token 时间
    config.auth.username = token; // eslint-disable-line
  }
  return config;
}, error => Promise.reject(error));

https.interceptors.response.use((response) => { // 请求后
  const res = response.data;
  return res; // eslint-disable-line
}, (error) => {
  console.log(error); // eslint-disable-line
  return false;
  // const lang = store.state.app.language;
  // const title = {
  //   en: 'Error',
  //   'zh-CN': '错误提示',
  //   'zh-TW': '錯誤提示',
  //   ko: '오류 힌트',
  // }
  // const msg1 = {
  //   en: 'Request error, please try again later.',
  //   'zh-CN': '请求错误，稍后再试',
  //   'zh-TW': '請求錯誤，稍後再試',
  //   ko: '요청을 요청하고, 잠시 후에 다시 시도해 보십시오.',
  // }
  // Notification({
  //   title: title[lang],
  //   message: msg1[lang],
  //   type: 'error'
  // });
  // return false;

  // if (!error.response) { // 请求出错
  //   Notification({
  //     title: title[lang],
  //     message: '请求超时，稍后再试',
  //     type: 'error'
  //   });
  //   return false;
  // }
  // switch (error.response.status) {
  //   case 504:
  //     Notification({
  //       title: title[lang],
  //       message: '网络错误，请检查后重试',
  //       type: 'error'
  //     });
  //     break;
  //   default:
  //     Notification({
  //       title: title[lang],
  //       message: '系统错误，请联系管理员',
  //       type: 'error'
  //     });
  //     break;
  // }
  // return false;
});

export default https;
